package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"manuscript-service/manuscriprpc/internal/svc"
	"manuscript-service/manuscriprpc/manuscriprpc"
	"manuscript-service/models/cache"
	"manuscript-service/models/mysql"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type ManuscriptListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewManuscriptListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ManuscriptListLogic {
	return &ManuscriptListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 列表
func (l *ManuscriptListLogic) ManuscriptList(in *manuscriprpc.ManuscriptListRequest) (*manuscriprpc.ManuscriptListResponse, error) {
	// todo: add your logic here and delete this line

	var lists []*manuscriprpc.ManuscriptList
	sprintf := fmt.Sprintf("manuscriptList")
	result, _ := cache.Rdb.Get(l.ctx, sprintf).Result()
	if result == "" {
		mysql.DB.Debug().Table("manuscripts").
			Select("manuscripts.id AS manuscript_id,  manuscripts.name,  content,  classes.name AS class_name").
			Joins("JOIN classes ON manuscripts.class_id = classes.id").
			Find(&lists)
		jsonList, _ := json.Marshal(lists)
		cache.Rdb.Set(l.ctx, sprintf, jsonList, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &lists)
	}

	return &manuscriprpc.ManuscriptListResponse{
		List: lists,
	}, nil
}
